const fs = require('fs');
const path = require('path');
const successTemp = require('./template.json');

function init(p, config) {
    for (const key in config) {
        const item = config[key];

        item.forEach(i => {
            i = i.substring(1).split('/');
            const currentPath = createDirectory(path.join(p, '/'), i);
            createFile(currentPath, i[i.length - 1], key.toUpperCase());
        });
    }

}

function createDirectory(p, item) {

    const name = item[0];
    let currentPath = path.join(p, name);
    if (item.length > 2) {
        item.splice(0, 1);
        const res = createDirectory(p + name + '/', item);
        currentPath = res;
    }

    if (fs.existsSync(path.join(p, name))) return currentPath;
    fs.mkdirSync(path.join(p, name));

    return currentPath;
}

function createFile(p, name, method) {
    const fileContext = {
        method,
        response: successTemp
    }
    try {
        fs.writeFileSync(path.join(p, name), JSON.stringify(fileContext), {
            flag: 'ax'
        });
    } catch (e) {
        console.log(`${name}文件已存在，跳过`);
    }

}


module.exports = init;
